码农之家

专注优质代码开发,为软件行业发展贡献力量

.net core 接口返回图片并且进行压缩

步骤:

1. 新建.net core 2.0 项目(过程略)

2. 通过nuget添加引用 System.Drawing.Common; .net core 开始的时候并没有System.Drawing,在2.0之后新增了 System.Drawing.Common,用于替代原来的System.Drawing.用法基本一致

3. 写接口了

a. 使用特性路由传入想要的尺寸和文件名,这样可以更好的用于前端展示,

b. 没有找到图片或者错误时返回默认的一张图片

c. 需要注意引用 using System.IO;using System.Drawing;

d. .net core 中返回图片不用 HttpResponseMessage 类型,而是直接采用 IActionResult. 而且封装了FileContentResult类,可以直接返回.

e. .net core 中获取当前项目的物理地址可以通过 AppContext.BaseDirectory 和.net 有区别

/// <summary>
        /// 访问图片
        /// </summary>
        /// <param name="width">所访问图片的宽度,高度自动缩放,大于原图尺寸或者小于等于0返回原图</param>
        /// <param name="name">所要访问图片的名称或者相对地址</param>
        /// <returns>图片</returns>
        [HttpGet]
        [Route("file/image/{width}/{name}")]
        public IActionResult GetImage(int width, string name)
        {
            var appPath = AppContext.BaseDirectory.Split("\bin\")[0] + "/image/";
            var errorImage = appPath + "404.png";//没有找到图片
            var imgPath = string.IsNullOrEmpty(name) ? errorImage : appPath + name;
            //获取图片的返回类型
            var contentTypDict = new Dictionary<string, string> {
                {"jpg","image/jpeg"},
                {"jpeg","image/jpeg"},
                {"jpe","image/jpeg"},
                {"png","image/png"},
                {"gif","image/gif"},
                {"ico","image/x-ico"},
                {"tif","image/tiff"},
                {"tiff","image/tiff"},
                {"fax","image/fax"},
                {"wbmp","image//vnd.wap.wbmp"},
                {"rp","image/vnd.rn-realpix"}
            };
            var contentTypeStr = "image/jpeg";
            var imgTypeSplit = name.Split('.');
            var imgType = imgTypeSplit[imgTypeSplit.Length - 1].ToLower();
            //未知的图片类型
            if (!contentTypDict.ContainsKey(imgType))
            {
                imgPath = errorImage;
            }
            else
            {
                contentTypeStr = contentTypDict[imgType];
            }
            //图片不存在
            if (!new FileInfo(imgPath).Exists)
            {
                imgPath = errorImage;
            }
            //原图
            if (width <= 0)
            {
                using (var sw = new FileStream(imgPath, FileMode.Open))
                { 
                    var bytes = new byte[sw.Length];
                    sw.Read(bytes, 0, bytes.Length);
                    sw.Close();
                    return new FileContentResult(bytes, contentTypeStr);
                }
            }
            //缩小图片
            using (var imgBmp = new Bitmap(imgPath))
            {
                //找到新尺寸
                var oWidth = imgBmp.Width;
                var oHeight = imgBmp.Height;
                var height = oHeight;
                if (width > oWidth)
                {
                    width = oWidth;
                }
                else
                {
                    height = width * oHeight / oWidth;
                }
                var newImg = new Bitmap(imgBmp, width, height);
                newImg.SetResolution(72, 72);
                var ms = new MemoryStream();
                newImg.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                var bytes = ms.GetBuffer();
                ms.Close();
                return new FileContentResult(bytes, contentTypeStr);
            }
        }

0 评论数